package com.lh_travel.lohas.activity.user;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lh_travel.lohas.R;
import com.lh_travel.lohas.base.api;
import com.lh_travel.lohas.base.baseActivity;
import com.lh_travel.lohas.domain.DafultMessageEvent;
import com.lh_travel.lohas.domain.UserBean;
import com.lh_travel.lohas.domain.respon;
import com.lh_travel.lohas.utils.Preferences;
import com.tamic.novate.Throwable;
import com.tamic.novate.callback.RxResultCallback;
import com.tamic.novate.callback.RxStringCallback;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

public class LoginActivity extends baseActivity {

    private ImageButton img_back;
    private Toolbar toolbar;
    private Button btn_confirm;
    private Button btn_send;
    private EditText ed_tel;
    private EditText ed_pwd;
    private myCountTimer timer;
    private ImageView img_login_qq;
    private ImageView img_login_wechat;
    private String type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

        findView();
        bindListner();
        ensureUI();
    }

    @Override
    public void findView() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        img_back = (ImageButton) findViewById(R.id.img_back);

        btn_confirm = (Button) findViewById(R.id.btn_confirm);
        btn_send = (Button) findViewById(R.id.btn_send);
        ed_tel = (EditText) findViewById(R.id.ed_tel);
        ed_pwd = (EditText) findViewById(R.id.ed_pwd);

        img_login_qq = (ImageView) findViewById(R.id.img_login_qq);
        img_login_wechat = (ImageView) findViewById(R.id.img_login_wechat);
    }

    @Override
    public void bindListner() {

        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (ed_tel.getText().toString().trim().length() < 11){

                    showMessage("请输入正确的手机号");

                }else if (ed_pwd.getText().toString().trim().length() == 0){

                    showMessage("请输入正确的验证码");

                }else {

                    showViewLoad();
                    new api(mContext).login(ed_tel.getText().toString().trim(), ed_pwd.getText().toString().trim(), loginCallBack);

                }

            }
        });

        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (ed_tel.getText().toString().trim().length() < 11){

                    showMessage("请输入正确的手机号");

                }else{

                    new api(mContext).sendCode(ed_tel.getText().toString().trim(), "login", new RxStringCallback() {
                        @Override
                        public void onNext(Object tag, String response) {
                            respon result = new Gson().fromJson(response, new TypeToken<respon>() {}.getType());

                            if (result.code.equals("200")){

                                timer = new myCountTimer(60000, 1000, btn_send);
                                timer.start();

                                showMessage("验证码以发送到您手机上");

                            }else {

                                showMessage(result.message);

                            }
                        }

                        @Override
                        public void onError(Object tag, Throwable e) {

                        }

                        @Override
                        public void onCancel(Object tag, Throwable e) {

                        }
                    });
                }
            }
        });

        img_login_qq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showViewLoad();
                type = "1";
                mApp.setPreference(Preferences.LOCAL.LOGINTYPE, "2");
                login_third(QQ.NAME);
            }
        });

        img_login_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showViewLoad();
                type = "1";
                mApp.setPreference(Preferences.LOCAL.LOGINTYPE, "3");
                login_third(Wechat.NAME);
            }
        });
    }

    private void login_third(String name) {
        Platform plat = ShareSDK.getPlatform(name);
        plat.removeAccount(true); //移除授权状态和本地缓存，下次授权会重新授权
        plat.SSOSetting(false); //SSO授权，传false默认是客户端授权，没有客户端授权或者不支持客户端授权会跳web授权
        plat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(final Platform platform, int i, HashMap<String, Object> hashMap) {

                new api(mContext).loginThird(platform.getDb().getUserId(), type, platform.getDb().getUserName(),
                        platform.getDb().getUserIcon(), "", "", "", new RxResultCallback<UserBean>() {
                            @Override
                            public void onNext(Object tag, int code, String message, UserBean response) {

                                if (code == 200) {

                                    mApp.setBeanPrefernce(Preferences.LOCAL.USERLOGIN, response);
                                    mApp.setPreference(Preferences.LOCAL.LOGINTYPE, "1");

                                    DafultMessageEvent event = new DafultMessageEvent();
                                    event.TAG = "LoginActivity";

                                    EventBus.getDefault().post(event);

                                    showMessage(message);
                                    dismissViewLoad();

                                    finish();

                                } else {

                                    //没绑定
                                    showMessage(message);
                                    showDialog(platform);
                                    dismissViewLoad();
                                }

                            }

                            @Override
                            public void onError(Object tag, Throwable e) {
                                dismissViewLoad();
                            }

                            @Override
                            public void onCancel(Object tag, Throwable e) {
                                dismissViewLoad();
                            }
                        });
            }

            @Override
            public void onError(Platform platform, int i, java.lang.Throwable throwable) {

                showMessage("发生未知错误");
                dismissViewLoad();

            }

            @Override
            public void onCancel(Platform platform, int i) {

                showMessage("取消第三方登录");
                dismissViewLoad();

            }
        });

        plat.showUser(null);
    }

    private void showDialog(final Platform platform) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.my_dialog, null);
        final AlertDialog mDialog = new AlertDialog.Builder(mContext)
                .setView(view).create();

        mDialog.setCancelable(false);

        final EditText ed_tel = (EditText) view.findViewById(R.id.ed_tel);
        final EditText ed_pwd = (EditText) view.findViewById(R.id.ed_pwd);

        final Button btn_send = view.findViewById(R.id.btn_send);

        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (ed_tel.getText().toString().trim().length() < 11) {

                    showMessage("请输入正确的手机号");

                } else {

                    new api(mContext).sendCode(ed_tel.getText().toString().trim(), "login", new RxStringCallback() {
                        @Override
                        public void onNext(Object tag, String response) {
                            respon result = new Gson().fromJson(response, new TypeToken<respon>() {
                            }.getType());

                            if (result.code.equals("200")) {

                                timer = new myCountTimer(60000, 1000, btn_send);
                                timer.start();

                                showMessage("验证码以发送到您手机上");

                            } else {

                                showMessage("失败");

                            }
                        }

                        @Override
                        public void onError(Object tag, Throwable e) {

                        }

                        @Override
                        public void onCancel(Object tag, Throwable e) {

                        }
                    });
                }
            }
        });


        view.findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String number = ed_tel.getText().toString().trim();
                String pwd = ed_pwd.getText().toString().trim();

                if (ed_tel.getText().toString().trim().length() < 11) {

                    showMessage("请输入正确的手机号");

                } else if (ed_pwd.getText().toString().trim().length() == 0) {

                    showMessage("请输入正确的验证码");

                } else {

                    showViewLoad();
                    new api(mContext).loginThird(platform.getDb().getUserId(), type, platform.getDb().getUserName(),
                            platform.getDb().getUserIcon(), "", number, pwd, new RxResultCallback<UserBean>() {
                                @Override
                                public void onNext(Object tag, int code, String message, UserBean response) {

                                    //已绑定
                                    if (code == 200) {

                                        mApp.setBeanPrefernce(Preferences.LOCAL.USERLOGIN, response);

                                        DafultMessageEvent event = new DafultMessageEvent();
                                        event.TAG = "LoginActivity";

                                        EventBus.getDefault().post(event);

                                        showMessage(message);
                                        dismissViewLoad();

                                        finish();
                                    } else {

                                        showMessage(message);
                                        dismissViewLoad();

                                    }
                                }

                                @Override
                                public void onError(Object tag, Throwable e) {
                                    dismissViewLoad();
                                    showMessage("服务器出错");
                                }

                                @Override
                                public void onCancel(Object tag, Throwable e) {
                                    dismissViewLoad();
                                    showMessage("服务器出错");
                                }
                            });
                }
            }
        });

        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                showMessage("登录失败");
                mDialog.dismiss();
            }
        });
        mDialog.show();
    }



    private RxResultCallback loginCallBack = new RxResultCallback<UserBean>() {
        @Override
        public void onNext(Object tag, int code, String message, UserBean response) {
            if (code == 200){

                mApp.setBeanPrefernce(Preferences.LOCAL.USERLOGIN, response);
                mApp.setPreference(Preferences.LOCAL.LOGINTYPE, "1");

                DafultMessageEvent event = new DafultMessageEvent();
                event.TAG = "LoginActivity";

                EventBus.getDefault().post(event);

                showMessage(message);
                dismissViewLoad();

                finish();

            }else {

                showMessage(message);
                dismissViewLoad();

            }
        }

        @Override
        public void onError(Object tag, Throwable e) {

            showMessage("登录失败");
            dismissViewLoad();

        }

        @Override
        public void onCancel(Object tag, Throwable e) {

        }
    };

    @Override
    public void ensureUI() {

        setSupportActionBar(toolbar);
        toolbar.setEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (timer != null){
            timer.cancel();
        }
    }

    private static class myCountTimer extends CountDownTimer {

        private Button btn;

        public myCountTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        public myCountTimer(long millisInFuture, long countDownInterval, Button btn) {
            super(millisInFuture, countDownInterval);
            this.btn = btn;
        }

        @Override
        public void onTick(long millisUntilFinished) {
            btn.setEnabled(false);
            btn.setText(millisUntilFinished/1000 +"秒后可重发");

        }

        @Override
        public void onFinish() {
            btn.setEnabled(true);
            btn.setText("发送验证码");
        }
    }
}
